#include "cluster.h"
#include "../util.h"

void Cluster::init_query(string line)
{
	int del1 = line.find("\t"), del2 = line.find("\t", del1 + 1);
	int freq = atoi(line.substr(0, del1).c_str());

	string query = line.substr(del1 + 1, del2 - del1 - 1);
	string feature_s = line.substr(del2 + 1, line.length() - del2 - 1);
	vector<string> qf_list = util::tokenize_h(feature_s, "\t");

	Query this_query(query);
	for(int i = 0; i < qf_list.size(); ++ i)
	{
		string v_f = qf_list[i];
		int del = v_f.find(":");
		int value = atoi(v_f.substr(0, del).c_str());
		string feature = v_f.substr(del + 1, v_f.length() - del - 1);
		this_query.add_feature(feature, value);		
	}
	graph.add_node(this_query);
	query2freq.insert(pair<string, int>(query, freq));
	size += freq;
}

void Cluster::display(iostream* out)
{
	vector<vector<string>> clusters;
	graph.flood(clusters);
	stringstream res;
	for(int i = 0; i < clusters.size(); ++ i)
	{
		stringstream group_info;
		group_info << i << "\t";
		int total = 0;
		map<int, vector<string>> sort_map;
		map<int, vector<string>>::iterator itr;
		int total_q = 0, cur_q = 0;
		for(int j = 0; j < clusters[i].size(); ++ j)
		{
			string query = clusters[i][j];
			total_q ++;
			int freq = (*query2freq.find(query)).second;
			itr = sort_map.find(-freq);
			if(itr == sort_map.end())
			{
				vector<string> v;
				v.push_back(query);
				sort_map.insert(pair<int, vector<string>>(-freq, v));
			}
			else
				(*itr).second.push_back(query);
			total += freq;
			
		}
		for(itr = sort_map.begin(); itr != sort_map.end(); ++ itr)
		{
			int freq = - (*itr).first;
			vector<string> &query_list = (*itr).second;
			for(int j = 0; j < query_list.size(); ++ j)
			{
				string query = query_list[j];
				group_info << query << "\t" << freq;
				if(++ cur_q < total_q)
					group_info << " | ";
			}
		}
		res << total << "\t" << group_info.str() << endl;
	}
	*out << res.str();
}